package com.fotkidemo.tasks;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import com.fotkidemo.beans.Image;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: roma
 * Date: 6/25/12
 * Time: 3:47 PM
 * To change this template use File | Settings | File Templates.
 */

//Класс отвечает за управление задачей асинхронной заргузки фоток и за отслеживание прогресса загрузки.
public final class TaskManager implements DialogInterface.OnCancelListener, IProgressTracker {
    private final OnTaskCompleteListener taskCompleteListener;
    private final ProgressDialog progressDialog;
    private LoadTask loadTask;

    public TaskManager(Context context, OnTaskCompleteListener taskCompleteListener) {
        this.taskCompleteListener = taskCompleteListener;
        progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(true);
        progressDialog.setOnCancelListener(this);
    }

    public void setupTask(LoadTask task, List<Image> images) {
        loadTask = task;
        loadTask.setProgressTracker(this);
        loadTask.execute(images);
    }

    @Override
    public void onCancel(DialogInterface dialogInterface) {
        loadTask.cancel(true);
        taskCompleteListener.onTaskComplete(loadTask);
        loadTask = null;
    }

    @Override
    public void onProgress(String message) {
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
        progressDialog.setMessage(message);
    }

    @Override
    public void onComplete() {
        progressDialog.dismiss();
        taskCompleteListener.onTaskComplete(loadTask);
        loadTask = null;
    }
}
